import json
from urllib.parse import quote
from flask import request, jsonify

from utils.initApp import mysql, default_response
from src import common

from . import share
from .service import ShareService


@share.route('/add', methods=['POST'])
def add():
    data = json.loads(request.get_data(as_text=True))
    token = common.get_token()

    values = dict()
    values['fileId'] = data['fileId']
    values['type'] = data['type']
    values['userId'] = token['userId']

    result = shareService.add(values)
    response = default_response.construct_response(result)
    return response


@share.route('/verify', methods=['POST'])
def verify():
    data = json.loads(request.get_data(as_text=True))

    values = dict()
    values['id'] = data['id']
    values['shareCode'] = data['shareCode']

    result, msg, code = shareService.verify(values)
    response = default_response.construct_response(result, msg, code)
    return response


@share.route('/delete/<share_id>', methods=['GET'])
def delete(share_id):

    values = dict()
    values['id'] = share_id

    result = shareService.delete(values)
    response = default_response.construct_response(result)
    return response


@share.route('/resource/<share_id>', methods=['GET'])
def resource(share_id):
    ranges = common.get_ranges()

    values = dict()
    values['id'] = share_id
    values["ranges"] = ranges

    result, code = shareService.resource(values)
    response = default_response.construct_file_response(result)
    return response, code


@share.route('/listAuth', methods=['GET'])
def list_auth():
    token = common.get_token()

    values = dict()
    values['userId'] = token['userId']

    result = shareService.list_auth(values)
    response = default_response.construct_response(result)
    return response


@share.route('/listPage', methods=['GET'])
def list_page():

    values = dict()
    values['name'] = request.args.get('name')

    result = shareService.list_page(values)
    response = default_response.construct_response(result)
    return response


shareService = ShareService(
    ['id', "userId", "type", "updateTime", "shareCode"])
